package repeat.personal.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.time.DateFormatUtils;
import org.springframework.web.multipart.MultipartFile;
import repeat.personal.exception.CompanyNameException;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;

/**
 * 、
 * 文件上传工具类服务
 *
 * @author: Zhanggq
 * @date: 2019/5/22 14:17
 **/
@Slf4j
public class FileUtil {

    public static final String prefix = "gzzj-property-punishment:";
    public static final String FILE_UPLOAD_ERR = prefix + "1001";
    public static final String UPLOAD_FILE_ALREADY_EXISTS = prefix + "1003";

    /**
     * 上传文件
     *
     * @param file     文件字节数字
     * @param filePath 路径
     * @param fileName 文件名称
     * @throws Exception
     */
    public static File uploadFile(byte[] file, String filePath, String fileName) throws Exception {

        File targetFile = new File(filePath);
        if (!targetFile.exists()) {
            targetFile.mkdirs();
        }
        FileOutputStream out = new FileOutputStream(filePath + fileName);
        out.write(file);
        out.flush();
        out.close();

        File fileResult = new File(filePath + fileName);

        return fileResult;
    }

    /**
     * 将文件存到指定文件夹,返回存储路径
     * @param multipartFile
     * @return
     */
    public static String getStorePath(MultipartFile multipartFile) {
        //获得本地临时存储路径
        String tmpStorePath = SystemInfoUtils.getTmpStorePath();
        //按照时间存储的相对路径
        String relativePath = DateFormatUtils.format(new Date(), "yyyy/MM/dd/HH/");
        //存储的文件名
        String uuidName = SystemInfoUtils.createUUIDName(multipartFile.getOriginalFilename());
        String uploadFileName = tmpStorePath + relativePath + uuidName;
        File file = new File(tmpStorePath + relativePath);
        //创建文件夹
        if (!file.exists()) {
            file.mkdirs();
        }
        file = new File(uploadFileName);
        if (file.exists()) {
            throw new CompanyNameException("文件已经上传！");
        }
        try {
            multipartFile.transferTo(file);
        } catch (IOException ioe) {
            throw new CompanyNameException("上传错误！", ioe);
        }
//        if (StringUtils.endsWith(uploadFileName, "/") == false) {
//            uploadFileName += "/";
//        }
        return uploadFileName;
    }
}
